import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.PriorityBlockingQueue;
class MyTask implements Comparable<MyTask>{
    //指定任务
    public Runnable runnable;
    //指定任务的时间,使用绝对时间戳
    public long time;
    public MyTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        //取当前的时间戳+传递的时间戳,作为该任务实际执行的时间戳
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }
}
class Mytimer{
    //带有优先级的阻塞队列
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    //构造任务
    //创建一个锁对象
    Object locker = new Object();
    //delay表示多久时间后执行
    public void schedule(Runnable runnable,long delay){
        MyTask task = new MyTask(runnable,delay);
        queue.put(task);
        //加入新的任务后唤醒等待中的线程
        locker.notify();
    }

    //构造线程,执行任务
    public Mytimer() {
        Thread t = new Thread(()->{
            while (true) {
                //从队列中取出任务
                synchronized (locker) {
                    try {
                        MyTask task = queue.take();
                        //获取当前系统时间和任务时间做比较
                        long time = System.currentTimeMillis();
                        if (task.time <= time) {
                            //满足条件,则开始执行任务
                            task.runnable.run();
                        } else {
                            //不满足要求,重新入队列
                            queue.put(task);
                            //让线程等待任务时刻和当前时刻相差的时间
                            locker.wait(time- task.time);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) {
//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                System.out.println("Hello World");
//            }
//        },2000);
    }
}
